import { createRouter, createWebHistory } from "vue-router";
import { userAPI } from '@/api/user';

// 路由角色常量
const ROLES = {
    USER: 'USER',
    BUSINESS: 'BUSINESS',
    ADMIN: 'ADMIN'
}

// 页面类型常量
const PAGE_TYPES = {
    PUBLIC: 'PUBLIC', // 公开页面
    AUTH_ONLY: 'AUTH_ONLY', // 仅需登录
    ROLE_BASED: 'ROLE_BASED' // 基于角色的页面
}

// 路由配置
const routes = [
    // 公开页面（无需登录）
    {
        path: "/",
        name: "Home",
        component: () => import('../views/Index.vue'),
        meta: {
            type: PAGE_TYPES.PUBLIC,
            title: "首页",
        }
    },
    {
        path: "/index",
        name: "Index",
        component: () => import('../views/Index.vue'),
        meta: {
            type: PAGE_TYPES.PUBLIC,
            title: "首页",
        }
    },
    {
        path: "/businessList",
        name: "BusinessList",
        component: () => import('../views/BusinessList.vue'),
        meta: {
            type: PAGE_TYPES.PUBLIC,
            title: "商家列表",
        }
    },
    {
        path: "/businessInfo",
        name: "BusinessInfo",
        component: () => import('../views/BusinessInfo.vue'),
        meta: {
            type: PAGE_TYPES.PUBLIC,
            title: "商家详情",
        }
    },
    {
        path: "/login",
        name: "Login",
        component: () => import('../views/Login.vue'),
        meta: {
            type: PAGE_TYPES.PUBLIC,
            title: "登录",
            hideFooter: true,
        }
    },
    {
        path: "/register",
        name: "Register",
        component: () => import('../views/Register.vue'),
        meta: {
            type: PAGE_TYPES.PUBLIC,
            title: "注册",
            hideFooter: true,
        }
    },
    {
        path: "/admin-login",
        name: "AdminLogin",
        component: () => import('../views/AdminLogin.vue'),
        meta: {
            type: PAGE_TYPES.PUBLIC,
            title: "管理员登录",
        }
    },

    // 用户专属页面
    {
        path: "/orders",
        name: "Orders",
        component: () => import('../views/Orders.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "订单确认",
            allowedRoles: [ROLES.USER]
        }
    },
    {
        path: "/payment",
        name: "Payment",
        component: () => import('../views/Payment.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "支付页面",
            allowedRoles: [ROLES.USER]
        }
    },
    {
        path: "/orderList",
        name: "OrderList",
        component: () => import('../views/OrderList.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "订单列表",
            allowedRoles: [ROLES.USER]
        }
    },
    {
        path: "/shoppingCart",
        name: "ShoppingCart",
        component: () => import('../views/ShoppingCart.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "购物车",
            allowedRoles: [ROLES.USER]
        }
    },
    {
        path: "/userAddress",
        name: "UserAddress",
        component: () => import('../views/UserAddress.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "我的地址",
            allowedRoles: [ROLES.USER]
        }
    },
    {
        path: "/wallet",
        name: "Wallet",
        component: () => import('../views/Wallet.vue'),
        meta: {
            type: PAGE_TYPES.AUTH_ONLY,
            title: "我的钱包"
        }
    },
    {
        path: "/transactionList",
        name: "TransactionList",
        component: () => import('../views/TransactionList.vue'),
        meta: {
            type: PAGE_TYPES.AUTH_ONLY,
            title: "交易记录"
        }
    },
    {
        path: "/userProfile",
        name: "UserProfile",
        component: () => import('../views/UserProfile.vue'),
        meta: {
            type: PAGE_TYPES.AUTH_ONLY,
            title: "我的"
        }
    },
    {
        path: "/personalInfo",
        name: "PersonalInfo",
        component: () => import('../views/PersonalInfo.vue'),
        meta: {
            type: PAGE_TYPES.AUTH_ONLY,
            title: "个人信息"
        }
    },
    {
        path: "/changePassword",
        name: "ChangePassword",
        component: () => import('../views/ChangePassword.vue'),
        meta: {
            type: PAGE_TYPES.AUTH_ONLY,
            title: "修改密码"
        }
    },
    {
        path: "/businessApplicationList",
        name: "BusinessApplicationList",
        component: () => import('../views/BusinessApplicationList.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "我的开店申请",
            allowedRoles: [ROLES.USER]
        }
    },
    {
        path: "/businessApplicationForm",
        name: "BusinessApplicationForm",
        component: () => import('../views/BusinessApplicationForm.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "开店申请",
            allowedRoles: [ROLES.USER]
        }
    },
    {
        path: "/businessApplicationForm/:id",
        name: "BusinessApplicationFormEdit",
        component: () => import('../views/BusinessApplicationForm.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "修改开店申请",
            allowedRoles: [ROLES.USER]
        }
    },
    {
        path: "/businessApplicationDetail/:id",
        name: "BusinessApplicationDetail",
        component: () => import('../views/BusinessApplicationDetail.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "申请详情",
            allowedRoles: [ROLES.USER]
        }
    },

    // 商家专属页面
    {
        path: "/BusinessEnd",
        name: "BusinessEnd",
        component: () => import('../views/BusinessEnd.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "商家后台",
            allowedRoles: [ROLES.BUSINESS]
        }
    },
    {
        path: "/business-data",
        name: "BusinessData",
        component: () => import('../views/BusinessData.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "商家数据",
            allowedRoles: [ROLES.BUSINESS]
        }
    },
    {
        path: "/business-orders",
        name: "BusinessOrders",
        component: () => import('../views/BusinessOrders.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "商家订单",
            allowedRoles: [ROLES.BUSINESS]
        }
    },
    {
        path: "/business-profile",
        name: "BusinessProfile",
        component: () => import('../views/BusinessProfile.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "商家信息",
            allowedRoles: [ROLES.BUSINESS]
        }
    },

    // 管理员专属页面
    {
        path: "/admin",
        name: "AdminDashboard",
        component: () => import('../views/AdminDashboard.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "管理员控制台",
            allowedRoles: [ROLES.ADMIN]
        }
    },
    {
        path: "/admin/dashboard",
        name: "AdminDashboardAlias",
        redirect: "/admin"
    },
    {
        path: "/admin/users",
        name: "UserManagement",
        component: () => import('../views/admin/UserManagement.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "用户管理",
            allowedRoles: [ROLES.ADMIN]
        }
    },
    {
        path: "/admin/applications",
        name: "ApplicationManagement",
        component: () => import('../views/admin/ApplicationManagement.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "申请管理",
            allowedRoles: [ROLES.ADMIN]
        }
    },
    {
        path: "/admin/businesses",
        name: "BusinessManagement",
        component: () => import('../views/admin/BusinessManagement.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "店铺管理",
            allowedRoles: [ROLES.ADMIN]
        }
    },
    {
        path: "/admin/withdraw-rules",
        name: "WithdrawRules",
        component: () => import('../views/WithdrawRules.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "提现规则管理",
            allowedRoles: [ROLES.ADMIN]
        }
    },
    {
        path: "/admin/recharge-rules",
        name: "RechargeRules",
        component: () => import('../views/RechargeRules.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "充值规则管理",
            allowedRoles: [ROLES.ADMIN]
        }
    },
    {
        path: "/admin/overdraft-rules",
        name: "OverdraftRules",
        component: () => import('../views/OverdraftRules.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "透支规则管理",
            allowedRoles: [ROLES.ADMIN]
        }
    },
    {
        path: "/admin/vip-levels",
        name: "VipLevelManagement",
        component: () => import('../views/VipLevelManagement.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "VIP等级管理",
            allowedRoles: [ROLES.ADMIN]
        }
    },
    {
        path: "/admin/applications/:id",
        name: "ApplicationDetail",
        component: () => import('../views/admin/ApplicationDetail.vue'),
        meta: {
            type: PAGE_TYPES.ROLE_BASED,
            title: "申请详情",
            allowedRoles: [ROLES.ADMIN]
        }
    },

    // 特殊页面
    {
        path: "/access-denied",
        name: "AccessDenied",
        component: () => import('../views/AccessDenied.vue'),
        meta: {
            type: PAGE_TYPES.PUBLIC,
            title: "访问受限"
        }
    },
];

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes,
});

// 修复重复导航错误
const originalPush = router.push;
router.push = function push(location) {
    return originalPush.call(this, location).catch((err) => {
        if (err.name !== "NavigationDuplicated") throw err;
        return err;
    });
};

// 工具函数：从权限信息中获取用户角色
function getUserRole(authorities) {
    if (!authorities || !Array.isArray(authorities)) return ROLES.USER;

    const authorityNames = authorities.map(auth =>
        typeof auth === 'string' ? auth : (auth.name || auth.authority)
    );

    if (authorityNames.includes('ADMIN')) return ROLES.ADMIN;
    if (authorityNames.includes('BUSINESS')) return ROLES.BUSINESS;
    return ROLES.USER;
}

// 工具函数：获取用户重定向路径
function getRedirectPath(userRole) {
    const redirectPaths = {
        [ROLES.USER]: '/index',
        [ROLES.BUSINESS]: '/BusinessEnd',
        [ROLES.ADMIN]: '/admin'
    };
    return redirectPaths[userRole] || '/index';
}

// 工具函数：检查是否有权限访问
function hasPermission(allowedRoles, userRole) {
    if (!allowedRoles || allowedRoles.length === 0) return true;
    return allowedRoles.includes(userRole);
}

// 路由守卫
router.beforeEach(async (to, from, next) => {
    // 设置页面标题
    if (to.meta.title) {
        document.title = to.meta.title;
    }

    const token = sessionStorage.getItem('token');
    const isLoggedIn = !!token;
    let userInfo = null;
    let userRole = null;

    // 如果已登录，获取用户信息
    if (isLoggedIn) {
        try {
            userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');

            // 如果sessionStorage中没有用户信息，则从API获取
            if (!userInfo.authorities) {
                userRole = sessionStorage.getItem('userRole');
            } else {
                userRole = sessionStorage.getItem('userRole');
            }
        } catch (error) {
            console.error('获取用户信息失败:', error);
            // 清除无效的登录状态
            sessionStorage.removeItem('token');
            sessionStorage.removeItem('userInfo');
            sessionStorage.removeItem('userRole');
            next('/login');
            return;
        }
    }
    console.log(userRole)
    // 根据页面类型进行权限检查
    switch (to.meta.type) {
        case PAGE_TYPES.PUBLIC:
            // 公开页面，任何人都可以访问
            if (isLoggedIn && to.meta.guestOnly) {
                // 已登录用户访问游客页面，重定向到对应角色首页
                next(getRedirectPath(userRole));
            } else {
                next();
            }
            break;

        case PAGE_TYPES.AUTH_ONLY:
            // 仅需登录的页面
            if (!isLoggedIn) {
                next({
                    path: '/login',
                    query: { redirect: to.fullPath, message: '请先登录' }
                });
            } else {
                userRole = sessionStorage.getItem('userRole');
                next();
            }
            break;

        case PAGE_TYPES.ROLE_BASED:
            // 基于角色的页面
            if (!isLoggedIn) {
                next({
                    path: '/login',
                    query: { redirect: to.fullPath, message: '请先登录' }
                });
            } else if (!hasPermission(to.meta.allowedRoles, userRole)) {
                // 角色权限不足
                // console.log("11111")
                // console.log(userRole)
                if (userRole === ROLES.BUSINESS) {
                    next('/access-denied');
                } else {
                    next('/access-denied');
                }
            } else {
                next();
            }
            break;

        default:
            next();
            break;
    }
});

router.afterEach((to, from) => {
    // 页面访问统计
    console.log(`路由切换: ${from.path} -> ${to.path}, 用户角色: ${sessionStorage.getItem('userRole') || '未登录'}`);
});

export default router;